package com.wyman.beans.factory;

import com.wyman.beans.BeanException;
import com.wyman.beans.PropertyValue;
import com.wyman.beans.PropertyValues;
import com.wyman.beans.factory.config.BeanDefinition;
import com.wyman.beans.factory.config.BeanFactoryPostProcessor;
import com.wyman.core.io.DefaultResourceLoader;
import com.wyman.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

/**
 * @Author 李伟民
 * @Description
 * @DateTime 2024/12/29 23:17
 */
//解析属性占位符 将配置文件中属性占位符相应的内容写入到beanDefinition 对应的属性中
public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {


    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    String location;
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeanException {
        try {
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            Properties properties = new Properties();
            properties.load(resource.getInputStream());

            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for (String definitionName : beanDefinitionNames) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(definitionName);

                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

                    Object value = propertyValue.getValue();
                    if (!(value instanceof String)) {
                        continue;
                    }

                    String strVal = (String) value;
                    StringBuilder sb = new StringBuilder(strVal);

                    int startInd = strVal.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
                    int endInd = strVal.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
                    //如果属性占位符符合条件
                    if (startInd != -1 && endInd != -1 && startInd < endInd) {
                        String propKey = strVal.substring(startInd + 2, endInd);
                        String propValue = properties.getProperty(propKey);
                        sb.replace(startInd, endInd + 1, propValue);
                        //不需要担心重复的问题 因为设置属性值会按照顺序设置 后面会覆盖前面的
                        propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(), sb.toString()));
                    }

                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    public void setLocation(String location) {
        this.location = location;
    }
}
